<template>
  <div class="warpper">

    <div class="form" @click="isgoprolist = false">
      <el-form ref="ruleForm" :model="formData" size="mini" label-width="160px" style="width:100%">
        <el-row :gutter="20" v-if="isEdit">
          <el-col :span="11">
            <el-form-item label="status" prop="status" style="width: 460px;">
              <template slot-scope="scope">
                <span>{{ formData.status }}</span>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="11" style="text-align: right;">
            <el-form-item v-if="formData.status !='approved'">
              <template slot-scope="scope">
                <el-button plain type="primary" v-permission="['saleinvoices.update']" @click="godisable(true)"
                  :disabled="isapproved"
                  v-if="formData.status =='pending' || formData.status =='rejection'">{{isdiable?"Edit":"Cancel Edit"}}</el-button>
                <el-button plain type="default" v-permission="['saleinvoices.void']" @click="editstatus(id, 'voided')"
                  :disabled="isapproved" v-if="formData.status =='pending'  && isdiable">Voided</el-button>
                <el-button plain type="danger" v-permission="['saleinvoices.rejection']"
                  @click="editstatus(id, 'rejection')" :disabled="isapproved"
                  v-if="formData.status =='pending'  && isdiable">Rejection</el-button>
                <el-button plain type="primary" v-permission="['saleinvoices.auditing']"
                  @click="editstatus(id, 'approved')" :disabled="isapproved"
                  v-if="formData.status =='pending' && isdiable">Auditing</el-button>
                <el-button plain type="default" @click="close()"
                  v-if="formData.status =='approved' || formData.status =='voided' || formData.status =='rejection'">Back</el-button>
              </template>
            </el-form-item>
            <el-form-item v-if="formData.status =='approved'">
              <template slot-scope="scope">
                <el-button plain type="default" @click="customerpayment()">Customer Payment</el-button>
                <el-button plain type="default" @click="prints(1)">Print Adress</el-button>
                <el-button plain type="default" @click="prints(2)">Print Invoice</el-button>
                <el-button plain type="default" @click="prints(3)">Print DO</el-button>
                <el-button plain type="default" @click="close()">Back</el-button>
              </template>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <el-dialog title="" :visible.sync="caigou1" width="65%" append-to-body @close="onCloseDialog">
      <div class="layui-fluid layui-anim layui-anim-upbit" id="print_body">
        <div class="layui-row layui-col-space15" style="padding: 30px;">
          <div class="layui-col-md12">
            <div class="layui-card">

              <!--              <div style="width: 100%;text-align: left;font-size: 22px;">
                <input value="MEIBAN TECHNOLOGIES (M) SDN BHD" class="layui-input"
                  style="padding-left: 0;border:0;width: 100%;text-align: left;font-size: 20px;font-weight: 400;">
              </div> -->

              <div class="layui-card-body">

                <div style="width: 100%;text-align: left;font-size: 22px;">
                  <input v-model="printform.billingtitle" class="layui-input"
                    style="padding-left: 0;border:0;width: 100%;text-align: left;font-size: 32px;">
                </div>
                <div style="width: 100%;text-align: left;font-size: 22px;">
                  <div
                    style="padding-left: 0;border:0;width: 100%;text-align: left;font-size: 25px;font-weight: 300;color:#060606">
                    {{printform.billingaddress}}
                  </div>
                  <div
                    style="padding-left: 0;border:0;width: 100%;text-align: left;font-size: 25px;font-weight: 300;color:#060606">
                    Tel: {{printform.billingtel}} Fax: {{printform.billingfax}}
                  </div>
                </div>
              </div>

              <!-- Print Address -->
              <div class="layui-card-body" style="padding-top:20px;">
                <div style="width: 100%;text-align: left;font-size: 12px;">
                  <input v-model="'Attn: '+printform.billingattention" class="layui-input"
                    style="padding-left: 0;border:0;width: 100%;text-align: left;font-size: 32px;">
                </div>
                <!--                <div style="width: 100%;text-align: left;font-size: 16px;">
                  <input value="Saravanan/Ravi(+6016-7056444)" class="layui-input"
                    style="padding-left: 0;border:0;width: 100%;text-align: left;font-size: 20px;font-weight: 300;">
                </div> -->
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="layui-inline ipt layui-col-md12" id="wdDs"
        style="text-align:right;margin:0 60px 20px 0;display: flex;align-items: center;justify-content: space-between">
        <span class="layui-btn print ipt" id="indfs"><i class="iconfont icon-font-61d" style="color: #fff;"></i></span>
        <el-button type="primary" v-print="'#print_body'">Print</el-button>
      </div>
    </el-dialog>

    <el-dialog title="" :visible.sync="caigou2" width="840px" @close="onCloseDialog">
      <div class="layui-fluid layui-anim layui-anim-upbit your-background-class" id="print_body2"
        style="background-image: url(https://v.ttxcx.net/static/img/fhzd.png);width: 840px;background-repeat: no-repeat;height: 1190px;background-size: cover;">

        <div>
          <input v-model="printform.ordernumber" class="ordernumber">
        </div>

        <div style="display: flex;padding-top: 165px;justify-content: space-between;">
          <div class="layui-row layui-col-space15" style="padding-left: 50px;">
            <div class="layui-col-md12">
              <div class="layui-card" style="width: 360px;">
                <div style="width: 100%;text-align: left;">
                  <input v-model="printform.billingtitle" class="layui-input"
                    style="padding-left: 0;border:0;width: 100%;text-align: left;font-size: 14px;font-weight: 600;">
                </div>
                <div class="layui-card-body">
                  <div style="width: 100%;text-align: left;height:80px;">
                    <input type="textarea" v-model="printform.billingaddress" class="layui-input"
                      style="padding-left: 0;border:0;width: 100%;text-align: left;font-size: 12px;">
                  </div>
                </div>
                <div class="layui-card-body">
                  <div style="width: 100%;text-align: left;">
                    <input v-model="'Tel: '+printform.billingtel+'                  Fax: '+printform.billingfax"
                      class="layui-input"
                      style="padding-left: 0;border:0;width: 100%;text-align: left;font-size: 14px;font-weight: 100;">
                  </div>
                  <div style="width: 100%;text-align: left;">
                    <input v-model="'Attn.'+printform.billingattention" class="layui-input"
                      style="padding-left: 0;border:0;width: 80%;text-align: left;font-size: 14px;font-weight: 100;">
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="layui-row layui-col-space15" style="padding-right: 5%;">
            <div class="layui-col-md12">
              <div class="layui-card" style="width: 360px">
                <div style="width: 100%;text-align: left;">
                  <input v-model="printform.deliverytitle" class="layui-input"
                    style="padding-left: 0;border:0;width: 100%;text-align: left;font-size: 14px;font-weight: 600;">
                </div>
                <div class="layui-card-body">
                  <div style="width: 100%;text-align: left;height:80px;">
                    <input type="textarea" v-model="printform.deliveryaddress" class="layui-input"
                      style="padding-left: 0;border:0;width: 100%;text-align: left;font-size: 12px;">
                  </div>
                </div>
                <div class="layui-card-body">
                  <div style="width: 100%;text-align: left;">
                    <input v-model="'Tel: '+printform.billingtel+'                  Fax: '+printform.billingfax"
                      class="layui-input"
                      style="padding-left: 0;border:0;width: 100%;text-align: left;font-size: 14px;font-weight: 100;">
                  </div>
                  <div style="width: 100%;text-align: left;">
                    <input v-model="'Attn.'+printform.billingattention" class="layui-input"
                      style="padding-left: 0;border:0;width: 100%;text-align: left;font-size: 14px;font-weight: 100;">
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div style="padding-top: 45px;">

          <div style="text-align: left;display: inline-block;width: 100px;padding-left: 50px">
            <input value="PI07" class="layui-input"
              style="padding-left: 0;border:0;text-align: left;font-size: 18px;width: 100px">
          </div>
          <div style="text-align: left;display: inline-block;width: 140px;margin-left: 100px;">
            <input v-model="printform.customernumber" class="layui-input"
              style="padding-left: 0;border:0;text-align: left;font-size: 18px;width: 140px;">
          </div>
          <div style="text-align: left;display: inline-block;width: 100px;margin-left: 65px;">
            <input v-model="printform.staff" class="layui-input"
              style="padding-left: 0;border:0;text-align: left;font-size: 18px;width: 95px">
          </div>
          <div style="text-align: left;display: inline-block;width: 70px;margin-left: 30px">
            <input v-model="printform.currency" class="layui-input"
              style="padding-left: 0;border:0;text-align: left;font-size: 18px;width: 70px">
          </div>
          <div style="text-align: left;display: inline-block;width: 70px;margin-left: 30px;">
            <input v-model="printform.creditterm" class="layui-input"
              style="padding-left: 0;border:0;text-align: left;font-size: 18px;width: 70px">
          </div>
          <div style="text-align: left;display: inline-block;width: 109px;">
            <input v-model="printform.delivery_at" class="layui-input"
              style="padding-left: 0;border:0;text-align: left;font-size: 18px;width: 109px">
          </div>

        </div>

        <div style="display: flex;padding-top: 40px;justify-content: space-between;">

          <div style="padding-left: 50px;width: 500px;">
            <div style="padding-left: 0;border:0;text-align: left;font-size: 18px;width: 460px;"
              v-for="(item, index) in printform.procureditem" :key="index" :item="item">
              <p>{{index+1}} {{ item.batchnumber}}/ {{ item.expirationdate}} /{{ item.qty}}</p>
              <p>{{ item.note}}</p>
            </div>
          </div>

          <div style="padding-left: 30px;width: 100px;">
            <div style="padding-left: 0;border:0;text-align: left;font-size: 18px;width: 70px;"
              v-for="(item, index) in printform.procureditem" :key="index" :item="item">
              <p>{{ item.qty}}</p>
            </div>
          </div>

          <div style="padding-left: 30px;width: 100px;">
            <div style="padding-left: 0;border:0;text-align: left;font-size: 18px;width: 70px;"
              v-for="(item, index) in printform.procureditem" :key="index" :item="item">
              <p>{{ item.costprice}}</p>
            </div>
          </div>

          <div style="padding-right: 5%;width: 100px;">
            <div style="padding-left: 0;border:0;text-align: left;font-size: 18px;width: 70px;"
              v-for="(item, index) in printform.procureditem" :key="index" :item="item">
              <p>{{ item.costamount}}</p>
            </div>
          </div>

        </div>

        <div style="display: flex;justify-content:space-evenly;position: relative;right: 0px;top: 300px;">
          <div style="border:0;text-align: left;font-size: 14px;">
            <p>SGD (Three Thousand Seven Hundred Seventy Only)</p>
          </div>
          <div style="border:0;text-align: left;font-size: 16px;width: 200px;">
            <p>TOTAL:SGD <span style="padding-left: 30px;">{{ printform.totalamount}}</span>
            </p>
          </div>
        </div>

      </div>
      <div class="layui-inline ipt layui-col-md12" id="wdDs"
        style="text-align:right;margin:0 60px 20px 0;display: flex;align-items: center;justify-content: space-between">
        <span class="layui-btn print ipt" id="indfs"><i class="iconfont icon-font-61d" style="color: #fff;"></i></span>
        <el-button type="primary" v-print="'#print_body2'">Print</el-button>
      </div>
    </el-dialog>

    <!-- Print DO -->
    <el-dialog title="" :visible.sync="caigou3" width="840px" @close="onCloseDialog">
      <div class="layui-fluid layui-anim layui-anim-upbit your-background-class" id="print_body3"
        style="padding: 0; background-image: url(https://v.ttxcx.net/static/img/fhuo.png);width: 840px;background-repeat: no-repeat;height: 1190px;background-size: cover;">


        <div>
          <input v-model="printform.ordernumber" class="ordernumber">
        </div>


        <div style="display: flex;padding-top: 165px;justify-content: space-between;">

          <div class="layui-row layui-col-space15" style="padding-left: 50px;">
            <div class="layui-col-md12">
              <div class="layui-card" style="width: 360px;">
                <div style="width: 100%;text-align: left;">
                  <input v-model="printform.billingtitle" class="layui-input"
                    style="padding-left: 0;border:0;width: 100%;text-align: left;font-size: 14px;font-weight: 600;">
                </div>
                <div class="layui-card-body">
                  <div style="width: 100%;text-align: left;height:80px;">
                    <input type="textarea" v-model="printform.billingaddress" class="layui-input"
                      style="padding-left: 0;border:0;width: 100%;text-align: left;font-size: 12px;">
                  </div>
                </div>
                <div class="layui-card-body">
                  <div style="width: 100%;text-align: left">
                    <input v-model="'Tel: '+printform.billingtel+'              Fax: '+printform.billingfax"
                      class="layui-input"
                      style="padding-left: 0;border:0;width: 100%;text-align: left;font-size: 14px;font-weight: 100;">
                  </div>
                  <div style="width: 100%;text-align: left;">
                    <input v-model="'Attn.'+printform.billingattention" class="layui-input"
                      style="padding-left: 0;border:0;width: 80%;text-align: left;font-size: 14px;font-weight: 100;">
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="layui-row layui-col-space15" style="padding-right: 5%;">
            <div class="layui-col-md12">
              <div class="layui-card" style="width: 360px;">
                <div style="width: 100%;text-align: left;">
                  <input v-model="printform.deliverytitle" class="layui-input"
                    style="padding-left: 0;border:0;width: 100%;text-align: left;font-size: 14px;font-weight: 600;">
                </div>
                <div class="layui-card-body">
                  <div style="width: 100%;text-align: left;height:80px;">
                    <input type="textarea" v-model="printform.deliveryaddress" class="layui-input"
                      style="padding-left: 0;border:0;width: 100%;text-align: left;font-size: 12px;">
                  </div>
                </div>
                <div class="layui-card-body">
                  <div style="width: 100%;text-align: left;">
                    <input v-model="'Tel: '+printform.billingtel+'              Fax: '+printform.billingfax"
                      class="layui-input"
                      style="padding-left: 0;border:0;width: 100%;text-align: left;font-size: 14px;font-weight: 100;">
                  </div>
                  <div style="width: 100%;text-align: left;">
                    <input v-model="'Attn.'+printform.billingattention" class="layui-input"
                      style="padding-left: 0;border:0;width: 100%;text-align: left;font-size: 14px;font-weight: 100;">
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div style="padding-top: 45px;">

          <div style="text-align: left;display: inline-block;width: 100px;padding-left: 50px">
            <input value="PI07" class="layui-input"
              style="padding-left: 0;border:0;text-align: left;font-size: 18px;width: 100px">
          </div>
          <div style="text-align: left;display: inline-block;width: 140px;margin-left: 100px;">
            <input v-model="printform.customernumber" class="layui-input"
              style="padding-left: 0;border:0;text-align: left;font-size: 18px;width:140px;">
          </div>
          <div style="text-align: left;display: inline-block;width: 80px;margin-left: 65px;">
            <input v-model="printform.staff" class="layui-input"
              style="padding-left: 0;border:0;text-align: left;font-size: 18px;width: 80px">
          </div>
          <div style="text-align: left;display: inline-block;width: 60px;margin-left: 55px">
            <input v-model="printform.currency" class="layui-input"
              style="padding-left: 0;border:0;text-align: left;font-size: 18px;width: 60px">
          </div>
          <div style="text-align: left;display: inline-block;width: 60px;margin-left: 40px;">
            <input v-model="printform.creditterm" class="layui-input"
              style="padding-left: 0;border:0;text-align: left;font-size: 18px;width: 60px">
          </div>
          <div style="text-align: left;display: inline-block;width: 109px;margin-left: 5px;">
            <input v-model="printform.delivery_at" class="layui-input"
              style="padding-left: 0;border:0;text-align: left;font-size: 18px;width: 109px">
          </div>

        </div>

        <div style="display: flex;padding-top: 40px;justify-content: space-between;">

          <div style="padding-left: 50px;width: 647px;">
            <div style="padding-left: 0;border:0;text-align: left;font-size: 18px;width: 500px;"
              v-for="(item, index) in printform.procureditem" :key="index" :item="item">
              <p>{{index+1}} {{ item.batchnumber}}/ {{ item.expirationdate}} /{{ item.qty}}</p>
              <p>{{ item.note}}</p>
            </div>
          </div>

          <div style="padding-right: 5%;width: 120px;">
            <div style="padding-left: 0;border:0;text-align: left;font-size: 18px;width: 90px;"
              v-for="(item, index) in printform.procureditem" :key="index" :item="item">
              <p>{{ item.qty}}</p>
            </div>
          </div>

        </div>
      </div>

      <div class="layui-inline ipt layui-col-md12" id="wdDs"
        style="text-align:right;margin-top:20px;margin-right:60px;display: flex;align-items: center;justify-content: space-between">
        <span class="layui-btn print ipt" id="indfs"><i class="iconfont icon-font-61d" style="color: #fff;"></i></span>
        <el-button type="primary" v-print="'#print_body3'">Print</el-button>
      </div>
    </el-dialog>



    <el-dialog title="Add Product" :visible.sync="dialogFormVisible" :close-on-click-modal="false"
      customClass="customWidth" width="80%">
      <div class="toolbar">
        <el-form :inline="true" :model="searchForm1" class="demo-form-inline" label-width="130px"
          label-position="right">
          <el-form-item label="Name">
            <el-input v-model="searchForm1.name" placeholder="Enter Name">
            </el-input>
          </el-form-item>

          <el-form-item label="Product SKU" label-width="130px">
            <el-input v-model="searchForm1.sku" placeholder="Enter SKU">
            </el-input>
          </el-form-item>

          <el-form-item label="Customer SKU">
            <el-input v-model="searchForm1.csku" placeholder="Enter SKU">
            </el-input>
          </el-form-item>
          <br />
          <el-form-item label="Category" prop="category_id">
            <treeselect v-model="searchForm1.category_id" :options="deptOptions" :normalizer="normalizer"
              placeholder="Select Category" @open="onOpen" @close="onClose" style="width: 188.4px;" />
          </el-form-item>

          <el-form-item label="Brand" prop="brand_id">
            <el-select v-model="searchForm1.brand_id" placeholder="Choose Brand" clearable style="width: 188.4px;">
              <el-option v-for="item in brand" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button @click="find1()" plain style="margin-left: 24px;">Search</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="table" style="width: 90%">
        <el-table :data="tableData1" size="small" stripe border style="margin-top: 20px;"
          @selection-change="handleSelectionChange">

          <el-table-column type="selection" width="50" align="center" :selectable="isRowSelectable" />

          <el-table-column prop="name" label="Name" width="100" align="center" />

          <el-table-column prop="sku" label="SKU" width="100" align="center" />

          <el-table-column label="Customer SKU" width="140" align="center">
            <template v-slot="scope">
              <span>{{ scope.row.csku }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="packaging" label="Packaging" width="100" align="center" />

          <el-table-column prop="uom" label="UOM" width="100" align="center" />

          <el-table-column label="Brand" width="100" align="center">
            <template v-slot="scope">
              <span>{{ scope.row.brand_name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="Category" align="center">
            <template v-slot="scope">
              <span>{{ scope.row.category_name }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="qty" label="QTY" width="100" align="center" />

          <el-table-column prop="price" label="Sale Price" width="120" align="center" />

          <el-table-column prop="remark" label="Remark" width="120" align="center" />
        </el-table>
      </div>

      <div class="page">
        <el-pagination v-if="isPaginate1" background :current-page="page1.current_page" :page-sizes="page1.sizes"
          :page-size="page1.per_page" layout="prev, pager, next" :total="page1.total" @size-change="sizeChange1"
          @current-change="currentChange1" />
      </div>

      <div class="dialog-footer" style="text-align: center; padding: 10px;">
        <el-button plain type="default" @click="dialogFormVisible=false">Back</el-button>
        <el-button type="primary" :disabled="multiplev" @click="handleadd">Add</el-button>
      </div>
    </el-dialog>


    <div class="form" id="cadd" @click="isgoprolist = false">

      <el-form ref="ruleForm" :model="formData" :rules="rules" size="mini" label-width="164px" style="width:95%"
        :disabled="isdiable">

        <el-row :gutter="20">

          <el-col :span="7">
            <el-form-item label="Customer Name" prop="customer_id" style="width: 460px;">
              <el-select v-model="formData.customer_id" placeholder="Select Customer" style="width:290px;"
                @change="changeterm" filterable remote :remote-method="remoteMethod">
                <el-option v-for="item in customers" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="Customer ID" prop="customer_id" style="width: 460px;">
              <el-select @change="changeterm" v-model="formData.customer_id" placeholder="Select Customerid"
                style="width:290px;" filterable remote :remote-method="remoteidMethod">
                <el-option v-for="item in customers" :key="item.id" :label="item.customerid" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>

          </el-col>
          <el-col :span="7">
            <el-form-item label="Delivery Date" prop="delivery_at" style="width:460px">
              <el-date-picker v-model="formData.delivery_at" type="date" value-format="yyyy-MM-dd" style="width:290px">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item label="Dedicated sales staff" prop="staff" style="width: 460px;">
              <el-select v-model="formData.staff" placeholder="Select Staff" style="width:290px">
                <el-option v-for="item in staff" :key="item.id" :label="item.name" :value="item.name">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="Customer credit" prop="customercredit" style="width:460px">
              <el-input v-model="formData.customercredit" style="width:290px" />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="Remark" prop="remark" style="width: 360px;">
              <el-input :rows="1" type="textarea" v-model="formData.remark" style="width:290px;"></el-input>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item label="Currency" prop="currency" style="width: 460px;">
              <el-select v-model="formData.currency" placeholder="Select Currency" style="width:290px;">
                <el-option v-for="item in currency" :key="item.id" :label="item.name" :value="item.name">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <!--            <el-form-item label="Order Number" prop="ordernumber" style="width:460px">
              <el-input v-model="formData.ordernumber" disabled />
            </el-form-item> -->
            <el-form-item label="Rate" prop="rate" style="width: 460px;">
              <el-input v-model="formData.rate" style="width:290px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="Reminder Date" prop="remindertime" style="width:460px">
              <el-date-picker v-model="formData.remindertime" type="date" style="width:290px" value-format="yyyy-MM-dd"
                @input="handleremindertimeChange">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">

          <el-col :span="7">
            <el-form-item label="Credit Term" prop="creditterm" style="width: 460px;">
              <el-input v-model="formData.creditterm" style="width:290px"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="7">
            <el-form-item label="Customer PO Number" prop="customernumber" style="width: 460px;">

              <el-select v-model="formData.customernumber" placeholder="Select Number" clearable filterable
                style="width:290px">
                <el-option v-for="item in quotationlist" :key="item.id" :label="item.ordernumber"
                  :value="item.ordernumber">
                </el-option>
              </el-select>


            </el-form-item>
          </el-col>
          <el-col :span="7">

            <el-form-item label="Create Date" prop="created_at" style="width:460px">
              <el-date-picker v-model="formData.addtime" type="date" style="width:290px" value-format="yyyy-MM-dd"
                @input="handleDateChange">
              </el-date-picker>
            </el-form-item>

          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item label="Billing Title" prop="billingtitle" style="width: 460px;">
              <el-select v-model="formData.billingtitle" placeholder="Select Title" filterable style="width:290px"
                @change="changebt">
                <el-option v-for="item in billingtitle" :key="item.id" :label="item.title" :value="item.title">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="Delivery Title" prop="deliverytitle" style="width: 460px;">
              <el-select v-model="formData.deliverytitle" placeholder="Select Title" filterable style="width:290px"
                @change="changedt">
                <el-option v-for="item in deliverytitle" :key="item.id" :label="item.title" :value="item.title">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="File" prop="certificates" style="width: 460px;">

              <div v-if="isdiable" style="position: relative;">
                <a v-if="formData.certificates" style="font-size: 12px;" :href="formData.certificates"
                  target="_blank"><img src="../../../assets/pdf.png" style="width: 40px;height: 40px" />
                </a>
                <i v-else class="el-icon-upload"> upload files </i>
              </div>

              <div v-else style="position: relative;">
                <el-upload ref="uploadAvatar" class="avatar-uploader" action="#" :show-file-list="false"
                  :on-change="changeAvatar" :auto-upload="true" :http-request="vgetUploadHandler()" name="file"
                  :limit="1">
                  <img v-if="formData.certificates" src="../../../assets/pdf.png" style="width: 40px;height: 40px" />
                  <i v-else class="el-icon-upload"> upload files </i>
                </el-upload>

                <div v-if="formData.certificates">
                  <a style="font-size: 12px;" :href="formData.certificates" target="_blank">view</a>
                  <span style="font-size: 12px;margin-left: 5px; color: red;" @click="vdelcart()">del</span>
                </div>
              </div>

            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item label="Billing Attention" prop="billingattention" style="width: 460px;">
              <el-input v-model="formData.billingattention" style="width:290px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="Delivery Attention" prop="deliveryattention" style="width: 460px;">
              <el-input v-model="formData.deliveryattention" style="width:290px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item label="Billing Fax" prop="billingfax" style="width: 460px;">
              <el-input v-model="formData.billingfax" style="width:290px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="Delivery Fax" prop="deliveryfax" style="width: 460px;">
              <el-input v-model="formData.deliveryfax" style="width:290px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item label="Billing Tel" prop="billingtel" style="width: 460px;">
              <el-input v-model="formData.billingtel" style="width:290px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="Delivery Tel" prop="deliverytel" style="width: 460px;">
              <el-input v-model="formData.deliverytel" style="width:290px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item label="Billing Address" prop="billingaddress" style="width: 460px;">
              <el-input v-model="formData.billingaddress" style="width:290px" :rows="3" type="textarea"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="Delivery Address" prop="deliveryaddress" style="width: 460px;">
              <el-input v-model="formData.deliveryaddress" style="width:290px" :rows="3" type="textarea"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
          </el-col>
        </el-row>

        <el-form-item class="cadd">

          <el-table ref="multipleTable" :data="formData.procureditem" prop="procureditem"
            :cell-style="{ 'text-align': 'center' }" :header-cell-style="{ 'text-align': 'center' }" border
            @mouseleave.native="handleRowMouseLeave" :summary-method="getSummaries" show-summary
            v-if="formData.procureditem && formData.procureditem.length > 0">
            <el-table-column label="NO" prop="" width="80">
              <template slot-scope="scope">
                <div @mouseenter="handleRowMouseEnter(scope.$index)">
                  <span>{{ scope.$index + 1 }}</span>
                  <img v-if="hoveredIndex==scope.$index" src="../../../assets/jiahao.png"
                    style="width: 20px;height: 20px" @click="oncopyproductname(scope.row, scope.$index)" />
                </div>
              </template>
            </el-table-column>
            <el-table-column label="ProductName" width="150px">
              <template slot-scope="scope">
                <el-input ref="inputRefs" v-model="scope.row.productname"
                  @input="onChangeproductname(scope.row.productname, scope.$index, $event)" :rows="3"
                  type="textarea"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="SKU" width="150px">
              <template slot-scope="scope">
                <el-input v-model="scope.row.sku" @input="onChangeproductsku(scope.row.sku, scope.$index, $event)"
                  :rows="3" type="textarea"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="Customer SKU" width="140px">
              <template slot-scope="scope">
                {{ scope.row.suppliesku }}
              </template>
            </el-table-column>
            <el-table-column label="On hand" width="80px">
              <template slot-scope="scope">
                {{ scope.row.onhand }}
              </template>
            </el-table-column>

            <el-table-column label="Pre QTY" width="100px">
              <template slot-scope="scope">
                {{ scope.row.preqty?scope.row.preqty:0 }}
              </template>
            </el-table-column>

            <el-table-column label="QTY" width="60px" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.qty" @blur="qty(scope.$index,$event)" type="text"
                  oninput="value=value.replace(/[^\d.]/g,'')" />
              </template>
            </el-table-column>
            <el-table-column label="UOM" width="60px">
              <template slot-scope="scope">
                {{ scope.row.unit }}
              </template>
            </el-table-column>

            <el-table-column label="Customer UOM" width="130px">
              <template slot-scope="scope">
                {{scope.row.cskuom}}
              </template>
            </el-table-column>

            <el-table-column label="Sale Price" width="100px">
              <template slot-scope="scope">
                <el-input v-model="scope.row.costprice" type="text" @input="handlePriceInput($event, scope.row)" />
              </template>
            </el-table-column>
            <el-table-column label="Sale Amount" width="140px">
              <template slot-scope="scope">
                <!-- <el-input v-model="scope.row.costamount = scope.row.qty * scope.row.costprice" disabled type="text"
                  oninput="value=value.replace(/[^\d.]/g,'')" /> -->
                {{ (scope.row.costamount = scope.row.qty * scope.row.costprice).toFixed(2) }}
              </template>
            </el-table-column>

            <el-table-column label="Batch Number" width="330px">
              <template slot-scope="scope">
                <div style="white-space: pre-wrap;width: 100%;">
                  <el-select v-model="scope.row.batchnumber" @change="changeProduct(scope.$index,$event)"
                    style="white-space: pre-wrap;width: 300px">
                    <el-option v-for="item in scope.row.batchnumberlist" :key="item.batchnumber"
                      :label="itemLabel(item)" :value="item.batchnumber" class="multiline-option"
                      style="white-space: pre-wrap;width: 300px">
                    </el-option>
                  </el-select>
                </div>
              </template>
            </el-table-column>

            <!-- <el-table-column label="Expiration Date" width="130px">
              <template slot-scope="scope">
                <el-date-picker v-model="scope.row.expirationdate" type="date" value-format="yyyy-MM-dd"
                  style="width: 130px;">
                </el-date-picker>
              </template>
            </el-table-column> -->
            <el-table-column label="Sales Order Number" width="130px">
              <template slot-scope="scope">
                <el-input v-model="scope.row.ordernumber"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="Note">
              <template slot-scope="scope">
                <el-input v-model="scope.row.note" :rows="3" type="textarea"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="Actions" width="110" v-if="isNew || (isEdit && !isdiable)">
              <template slot-scope="scope">
                <el-button plain type="danger" v-permission="['saleinvoices.destroy']" @click="removeItem(scope.row)"
                  size="mini">delete</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!--          <div style="text-align: center; font-weight: bold;">
            <span>Total QTY: {{ totalqty }}</span>
            <span> | Total Sale Amount: {{ totalamount.toFixed(2) }}</span>
          </div> -->

          <el-table :data="tableDatav" size="small" stripe border style="width: 100%;display:none" align="center"
            class="tableDatav">

            <el-table-column label="NO" prop="" width="80">
              <template slot-scope="scope">
                Total
              </template>
            </el-table-column>
            <el-table-column label="ProductName" width="150px">
              <template slot-scope="scope">

              </template>
            </el-table-column>
            <el-table-column label="SKU" width="150px">
              <template slot-scope="scope">

              </template>
            </el-table-column>
            <el-table-column label="Customer SKU" width="140px">
              <template slot-scope="scope">

              </template>
            </el-table-column>
            <el-table-column label="On hand" width="80px">
              <template slot-scope="scope">

              </template>
            </el-table-column>

            <el-table-column label="Pre QTY" width="100px">
              <template slot-scope="scope">

              </template>
            </el-table-column>

            <el-table-column label="QTY" width="60px" align="center">
              <template slot-scope="scope">
                <span>{{ totalqty }}</span>
              </template>
            </el-table-column>
            <el-table-column label="UOM" width="60px">
              <template slot-scope="scope">

              </template>
            </el-table-column>

            <el-table-column label="Customer UOM" width="130px">
              <template slot-scope="scope">

              </template>
            </el-table-column>

            <el-table-column label="Sale Price" width="100px">
              <template slot-scope="scope">

              </template>
            </el-table-column>
            <el-table-column label="Sale Amount" width="140px">
              <template slot-scope="scope">
                <span>{{totalamount.toFixed(2)}}</span>
              </template>
            </el-table-column>

            <el-table-column label="Batch Number" width="330px">
              <template slot-scope="scope">

              </template>
            </el-table-column>

            <!-- <el-table-column label="Expiration Date" width="130px">
              <template slot-scope="scope">

              </template>
            </el-table-column> -->
            <el-table-column label="Sales Order Number" width="130px">
              <template slot-scope="scope">

              </template>
            </el-table-column>
            <el-table-column label="Note">
              <template slot-scope="scope">

              </template>
            </el-table-column>
            <el-table-column label="Actions" width="110" v-if="isNew || (isEdit && !isdiable)">
              <template slot-scope="scope">

              </template>
            </el-table-column>







          </el-table>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer" style="margin-left: 170px;" v-if="isNew || (isEdit && !isdiable)">
        <el-button type="primary" @click="addItem" :disabled="isdiable">Add Product</el-button>
        <el-button type="primary" @click="productadd()" :disabled="isdiable">Precise Search</el-button>
        <el-button type="primary" @click="productsaleorder()" :disabled="isdiable">Add by Sale Order</el-button>
        <br><br>
        <el-button type="primary" @click="saveHandle('ruleForm')" :disabled="isdiable || isubmit"
          style="margin-left: 300px;">Submit</el-button>
        <el-button type="default" @click="close()">Cancel</el-button>
      </div>
    </div>

    <div class="form plt" v-if="isgoprolist" :style="{ 'top': topx,'left':'600px' }">
      <el-button @click="isgoprolist = false" size="mini"
        style="position: absolute;right: 20px;top: 20px;z-index: 999;height: 40px;color: red;">X</el-button>
      <div class="table">
        <el-table :data="tableData" size="small" @row-click="handleRowClicks" stripe border style="width: 100%"
          height="320">
          <el-table-column prop="name" label="Name" width="120" align="center" />
          <el-table-column prop="sku" label="SKU" min-width="100" />
          <el-table-column label="Spec" width="100" align="center">
            <template v-slot="scope">
              <span>{{ scope.row.uom }}{{ scope.row.uom_sku }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="quantity" min-width="100" />
          <el-table-column prop="packaging" label="Packaging" min-width="100" />
          <el-table-column prop="price" label="Price(S$)" width="100" />
          <el-table-column prop="batchnumber" label="Batch Number" width="160" />
          <el-table-column prop="availableqty" label="Available qty" width="140" />
          <!-- <el-table-column label="Actions" width="200">
            <template slot-scope="scope">
              <el-button plain @click="selectadd(scope.row)">select</el-button>
            </template>
          </el-table-column> -->
        </el-table>
        <!-- <div slot="footer" class="dialog-footer" style="margin-left: 50%;margin-top: 10px;">
          <el-button @click="isgoprolist = false" size="mini">close</el-button>
        </div> -->
      </div>
    </div>

    <div class="form">
      <el-dialog title="Add by Sale Order" :visible.sync="dialogFormVisible1" :close-on-click-modal="false"
        customClass="customWidth" width="60%">
        <div class="toolbar">
          <div class="table" style="width: 90%">
            <el-table :data="tableData2" size="small" stripe border style="margin-top: 20px;" ref="singleSelectTable"
              @row-click="handleRowClick">

              <!-- <el-table-column type="selection" width="50" align="center" /> -->

              <el-table-column label="Order Type" align="center">
                <template v-slot="scope">
                  <span>Sale Order</span>
                </template>
              </el-table-column>
              <el-table-column prop="ordernumber" label="Sale Order Number" align="center" />

              <el-table-column label="Order Created Date" min-width="120">
                <template v-slot="scope">
                  <span>{{ scope.row.created_at | showDateTime }}</span>
                </template>
              </el-table-column>
              <el-table-column label="Select Items" width="140" align="center">
                <template v-slot="scope">
                  <el-tag type="success" v-if="scope.row === selectedRow">
                    In Progress
                  </el-tag>
                  <span v-else>In Progress</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="page">
            <el-pagination v-if="isPaginate2" background :current-page="page2.current_page" :page-sizes="page2.sizes"
              :page-size="page2.per_page" layout="prev, pager, next" :total="page2.total" @size-change="sizeChange2"
              @current-change="currentChange2" />
          </div>
        </div>

        <div class="table" style="width: 90%">
          <el-table :data="tableDataorder" size="small" stripe border style="margin-top: 20px;"
            @selection-change="handleSelectionChangeorder">

            <el-table-column type="selection" width="50" align="center" :selectable="isRowSelectableorder" />

            <el-table-column label="Product Name/SKU" width="180" align="center">
              <template v-slot="scope">
                <span>{{scope.row.productname}}/{{scope.row.sku}}</span>
              </template>
            </el-table-column>

            <el-table-column label="Order QTY" align="center">
              <template v-slot="scope">
                <span>{{scope.row.qty}}</span>
              </template>
            </el-table-column>

            <el-table-column label="Citation QTY" align="center">
              <template v-slot="scope">
                <el-input v-model="scope.row.lsyynumber" style="width: 65%;"
                  @blur="handleUpdatesc(scope.row, scope.$index)"
                  :disabled="scope.row.islsyynumber || scope.row.yynumber?false:true" />
              </template>
            </el-table-column>

            <el-table-column label="Remaining QTY" align="center">
              <template v-slot="scope">
                <span>{{scope.row.yynumber?scope.row.yynumber:0}}</span>
              </template>
            </el-table-column>

            <el-table-column label="Unit" align="center">
              <template v-slot="scope">
                <span>{{scope.row.unit}}</span>
              </template>
            </el-table-column>

          </el-table>
        </div>
        <div class="dialog-footer" style="text-align: center;padding-bottom: 20px;">
          <el-button plain type="default" @click="dialogFormVisible1=false">Cancel</el-button>
          <el-button type="primary" :disabled="multiplevo" @click="handleorderadd">Quote</el-button>
        </div>
      </el-dialog>
    </div>


    <el-dialog class="bba" title="Customer payment" :visible.sync="payment" :close-on-click-modal="false"
      customClass="customWidth" width="60%">

      <el-form ref="form" :model="form" label-width="200px">
        <el-form-item label="Total Amount" style="align-items: center;">
          {{formData.totalamount}}
        </el-form-item>
        <el-form-item label="Received" style="align-items: center;">
          {{formData.allapayment}}
        </el-form-item>
        <el-form-item label="Total Amount" style="align-items: center;">
          {{parseInt(formData.totalamount)-parseInt(formData.allapayment)-parseInt(received)}}
        </el-form-item>
        <el-form-item label="Received account">
          <el-input v-model="received" autocomplete="off" type="text" style="width:290px"
            :disabled="parseInt(formData.allapayment)>=parseInt(formData.totalamount)" />
        </el-form-item>
        <el-form-item label="Amount received this time">
          <el-date-picker v-model="recevicetime" type="date" value-format="yyyy-MM-dd" style="width:290px">
          </el-date-picker>
        </el-form-item>
      </el-form>

      <div class="table" style="width: 90%">
        <div class="el-dialog__header" style="padding-left: 0;"><span class="el-dialog__title">Payment Record</span>
        </div>
        <el-table :data="formData.saleinvoicepaymentsitem" size="small" stripe border style="margin-top: 20px;">

          <el-table-column type="selection" width="50" align="center" />

          <el-table-column label="received" width="180" align="center">
            <template v-slot="scope">
              <span>{{scope.row.received}}</span>
            </template>
          </el-table-column>

          <el-table-column label="recevicetime" align="center">
            <template v-slot="scope">
              <span>{{scope.row.recevicetime}}</span>
            </template>
          </el-table-column>

          <el-table-column label="admin" align="center">
            <template v-slot="scope">
              <span>{{scope.row.adminame}}</span>
            </template>
          </el-table-column>

        </el-table>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="payment = false">Cancel</el-button>
        <el-button type="primary" @click="savepayment"
          :disabled="parseInt(formData.allapayment)>=parseInt(formData.totalamount)">Save</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import CURD from "@/mixin/CURD";
  import {
    index,
    show,
    update,
    store
  } from "@/api/saleinvoice";
  import {
    index as billingindex,
  } from "@/api/attention";
  import {
    index as deliveryindex,
  } from "@/api/customeraddre";

  import {
    index as warehouselist
  } from "@/api/warehouse";
  import {
    index as quotationlistindex
  } from "@/api/quotationlist";
  import {
    index as skulist,
    update as skupdate
  } from "@/api/sku";
  import {
    store as uploadImg
  } from "@/api/medias";
  import {
    index as superindex
  } from "@/api/supplier";
  import {
    index as prowarlist
  } from "@/api/inventory";
  import {
    store as saleinvoicepaymentadd
  } from "@/api/saleinvoicepayment";
  import {
    index as inventorywaylist
  } from "@/api/inventoryway";
  import {
    index as customerindex
  } from "@/api/customer";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import {
    index as cateindex,
  } from "@/api/product_category";
  import {
    index as brandindex
  } from "@/api/brand";
  import {
    index as adminindex
  } from "@/api/admin";
  import {
    show as saleordershow,
  } from "@/api/saleorder";
  import {
    truncate
  } from "fs";
  export default {
    name: "saleinvoiceadd",
    mixins: [CURD],
    components: {
      Treeselect
    },
    data() {
      return {
        hoveredIndex: null, // 用于存储当前悬停的行索引
        selectedRow: null, // 当前选中的行
        selectedRowKey: 0, // 用于强制重新渲染表格的 key
        tableDataorder: [],
        isPaginate1: true,
        page1: {
          total: null,
          per_page: 5,
          sizes: [10, 20, 25, 50],
          current_page: 1
        },
        tableData1: [],
        isPaginate2: true,
        page2: {
          total: null,
          per_page: 10,
          sizes: [10, 20, 25, 50],
          current_page: 1
        },
        searchForm1: {},
        printform: {},
        caigou1: false,
        caigou2: false,
        caigou3: false,
        quotationlist: [],
        isubmit: false,
        rowIndex: 0,
        x: 0,
        y: 0,
        topx: '60%',
        isgoprolist: false,
        isdiable: true,
        staff: [{
          id: "KW",
          name: "KW",
        }],
        currency: [{
          id: 1,
          name: "SGD",
        }, {
          id: 2,
          name: "USD",
        }],
        id: null,
        isEdit: false,
        isNew: false,
        formData: {
          rate: 1,
          staff: "KW",
          procureditem: [],
        },
        received: 0,
        module: "saleinvoice",
        newTitle: "New saleinvoice",
        editTitle: "Edit saleinvoice",
        isPaginate: true,
        isUploadFile: false,
        fileReader: new FileReader(),
        isShow: false,
        imageUrl: "",
        customers: [],
        suppliers: [],
        warehouse: [],
        billingtitle: [],
        deliverytitle: [],
        xiabiao: -1,
        tindex: 0,
        tableData: [],
        searchForm: {

        },
        form: {},
        isapproved: false,
        inputElements: [],
        tableDatav: [{
          id: "approved",
          name: "approved",
        }],
        categories: [],
        deptOptions: [],
        customersid: [],
        ids: [],
        oidlist: [],
        productdata: [],
        brand: [],
        tableData2: [],
        sids: [],
        multiplevs: false,
        multiplev: false,
        idso: [],
        multiplevo: true,
        dialogFormVisible1: false,
        warehouseid: "",
        payment: false,
        recevicetime: "",
        gotosaleordernumber: ""
      };
    },
    mounted() {

    },
    watch: {
      'formData.procureditem': {
        handler() {
          //this.updateInputElements();
        },
        deep: true
      }
    },
    computed: {
      totalqty() {
        if (this.formData.procureditem) {
          const totalPrice = this.formData.procureditem.reduce((total, item) => total + parseFloat(item
            .qty), 0);
          return totalPrice ? totalPrice : 0
        }
      },
      totalamount() {
        if (this.formData.procureditem) {
          const amount = this.formData.procureditem.reduce((total, item) => total + parseFloat(item.costamount), 0);
          return amount ? amount : 0
        }
      },
    },
    async created() {

      this.oid = this.$route.query.oid
      if (this.oid > 0) {
        this.isNew = true
        this.isEdit = false
        this.formData.status = "pending"
        this.isdiable = false
        try {
          const {
            data
          } = await saleordershow(this.oid);
          console.log(data)
          this.formData = data;
        } catch (error) {
          console.error('Failed to fetch saleordershow:', error);
        }
        console.log("fsdfsdfsdfsd")

        var numStr = "01";
        const {
          data
        } = await index(1, 1);
        var lslist = data;
        if (data.length > 0) {
          var dqskinid = lslist[0].id + 1
          numStr = dqskinid.toString();
        }
        this.isNew = true
        this.formData.status = "pending"
        this.isdiable = false
        const currentDate = new Date();
        const year = currentDate.getFullYear();
        const month = currentDate.getMonth() + 1;
        const day = currentDate.getDate();
        console.log(`${year}-${month}-${day}`);
        this.formData.addtime = `${year}-${month}-${day}`
        this.formData.ordernumber = "IN" + `${year}`.slice(-2) + "-" + numStr.padStart(4, '0')


      } else {

        this.id = this.$route.query.id
        if (this.id > 0) {
          this.isEdit = true
          const {
            data
          } = await show(this.id);
          this.formData = data;
          if (this.formData.status == "approved") {
            this.isapproved = true
          }

        } else {

          var numStr = "01";
          const {
            data
          } = await index(1, 1);
          var lslist = data;
          if (data.length > 0) {
            var dqskinid = lslist[0].id + 1
            numStr = dqskinid.toString();
          }
          this.isNew = true
          this.formData.status = "pending"
          this.isdiable = false
          const currentDate = new Date();
          const year = currentDate.getFullYear();
          const month = currentDate.getMonth() + 1;
          const day = currentDate.getDate();
          console.log(`${year}-${month}-${day}`);
          this.formData.addtime = `${year}-${month}-${day}`
          this.formData.ordernumber = "IN" + `${year}`.slice(-2) + "-" + numStr.padStart(4, '0')
          this.addItem()
          this.$nextTick(() => {
            const inputElement = document.querySelector(`.el-table__row input:nth-child(${1})`);
            if (inputElement) {
              if (inputElement) {
                const inputRect = inputElement.getBoundingClientRect();
                this.y = inputRect.left
                this.x = inputRect.top - 100
                console.log('Input coordinates:', this.x, this.y);
              }
            }
          });
        }

      }
      try {
        const {
          data
        } = await customerindex(1, 100);
        this.customers = data;
      } catch (error) {
        console.error('Failed to fetch customer:', error);
      }
      try {
        const {
          data
        } = await customerindex(1, 20, {
          cid: 21
        });
        this.customersid = data;
      } catch (error) {
        console.error('Failed to fetch customer:', error);
      }
      try {
        const {
          data
        } = await quotationlistindex(1, 100);
        this.quotationlist = data;
      } catch (error) {
        console.error('Failed to fetch customer:', error);
      }
      try {
        const {
          data
        } = await brandindex(1, 100); // 假设index是一个异步函数
        this.brand = data;
      } catch (error) {
        console.error('Failed to fetch brand:', error);
      }
      // try {
      //   const {
      //     data
      //   } = await warehouselist(1, 100);
      //   this.warehouse = data;
      // } catch (error) {
      //   console.error('Failed to fetch warehouse:', error);
      // }
      try {
        const {
          data
        } = await cateindex(1, 100);
        this.categories = data;
        this.deptOptions = this.handleTree(data, "id", "parent_id");
      } catch (error) {
        console.error('Failed to fetch categories:', error);
      }

      try {
        const {
          data
        } = await adminindex(1, 100, {
          usertype: 1
        });
        this.staff = data.map(item => ({
          id: item.id, // 将 nickname 的值赋给 id
          name: item.nickname // 将 nickname 的值赋给 name
        }));

      } catch (error) {
        console.error('Failed to fetch staff:', error);
      }
    },
    methods: {
      remoteMethod(query) {
        if (query !== '') {
          this.loading = true;
          console.log(query, "dddddddddddddddddddddddd")
          setTimeout(() => {
            this.loading = false;
            try {
              customerindex(1, 100, {
                name: query
              }).then(res => {
                this.customers = res.data
              });
              this.$nextTick(() => {
                this.$forceUpdate()
              })
            } catch (error) {
              console.error('Failed to fetch customer:', error);
            }
          }, 200);
        } else {
          this.customers = [];
        }
      },
      remoteidMethod(query) {
        if (query !== '') {
          this.loading = true;
          console.log(query, "dddddddddddddddddddddddd")
          setTimeout(() => {
            this.loading = false;
            try {
              customerindex(1, 100, {
                customerid: query
              }).then(res => {
                this.customers = res.data
              });
              this.$nextTick(() => {
                this.$forceUpdate()
              })
            } catch (error) {
              console.error('Failed to fetch customer:', error);
            }
          }, 200);
        } else {
          this.customers = [];
        }
      },
      getSummaries(param) {
        const {
          columns,
          data
        } = param;
        const sums = [];

        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = 'Total';
            return;
          }
          if (index === 6) {
            const totalQuantity = data.reduce((sum, row) => {
              return parseFloat((sum + (parseFloat(row.qty) || 0)).toFixed(2));
            }, 0);
            sums[index] = totalQuantity.toFixed(2);
          } else if (index === 10) {
            const totalWeight = data.reduce((sum, row) => {
              return parseFloat((sum + (parseFloat(row.costamount) || 0)).toFixed(2));
            }, 0);
            sums[index] = totalWeight.toFixed(2);
          } else {
            sums[index] = '';
          }
        });

        return sums;
      },
      itemLabel(item) {
        return item.batchnumber + '--EX' + item.expirationdate + '-QTY：' + item.quantity;
      },
      vdelcart() {
        console.log("vdelcartvdelcart")
        this.formData.certificates = ""
        this.$forceUpdate()
      },
      vgetUploadHandler() {
        return (options) => {
          this.uploadHandlev(options);
        };
      },
      async uploadHandlev(options) {
        const file = options.file;
        if (file) {
          this.fileReader.readAsDataURL(file);
        }
        this.fileReader.onload = () => {
          const formData = new FormData();
          formData.append("file", file);
          uploadImg(formData)
            .then((res) => {
              console.log(res)
              var {
                data
              } = res;
              this.$message.success(res.status);
              this.formData.certificates = data.url
              this.$forceUpdate()
            })
            .catch((err) => {
              if (err.response.status === 422) {
                const {
                  info,
                  fileName
                } = err.response.data;
                this.$message.error(info);
              }
            });
        };

      },

      handleRowClick(row) {
        this.selectadd(row);
      },
      handlePriceInput(value, row) {
        // 移除非数字和小数点
        value = value.replace(/[^\d.]/g, '');
        // 确保只有一个小数点
        if (value.split('.').length > 2) {
          value = value.replace(/\.+$/, '');
        }
        // 限制小数点后两位
        if (value.includes('.')) {
          const parts = value.split('.');
          value = parts[0] + '.' + parts[1].slice(0, 2);
        }
        // 更新值
        row.costprice = value;
      },

      handleRowClicks(row) {
        this.selectadd(row);
      },
      async customerpayment() {
        var that = this
        console.log(that.id)
        try {
          const {
            data
          } = await show(that.id);
          that.formData = data;
        } catch (error) {
          console.error('Failed to fetch saleordershow:', error);
        }
        that.payment = true
      },
      handleRowMouseEnter(v) {
        this.hoveredIndex = v;
      },
      handleRowMouseLeave() {
        this.hoveredIndex = null; // 鼠标离开时重置悬停索引
      },
      oncopyproductname(row, index) {
        console.log(row.preqty, "在途库存")
        this.xiabiao = this.xiabiao + 1
        this.formData.procureditem.push({
          index: this.xiabiao,
          productname: row.productname,
          sku: row.sku,
          suppliesku: row.suppliesku,
          onhand: row.onhand,
          qty: row.qty,
          unit: row.unit,
          cskuom: row.cskuom,
          preqty: row.preqty,
          costprice: row.costprice,
          costamount: row.costamount,
          saleprice: row.saleprice,
          expirationdate: row.expirationdate,
          batchnumberlist: row.batchnumberlist,
          certificates: row.certificates,
          batchnumber: row.batchnumber,
          note: row.note,
          product_id: row.product_id,
          ordernumber: row.ordernumber,
        });
        console.log(this.formData.procureditem, "psss")
      },
      handleUpdatesc(row, index) {
        console.log(row, "dsdsdsd")
        if (parseInt(row.lsyynumber) > parseInt(row.yynumber)) {
          console.log("我已经更新 了啊，怎么还是以前的效果。你到了这里，我就已经修改了")
          this.tableDataorder[index].lsyynumber = ''
          this.$set(this.tableDataorder[index], 'lsyynumber', '')
          this.$message.error("Please fill in the correct number")
          //this.$forceUpdate()
        } else {
          return false;
          this.$confirm('This operation will update the data. Do you want to continue?', 'title', {
            confirmButtonText: 'confirm',
            cancelButtonText: 'cancel',
            type: 'warning'
          }).then(() => {
            // const id = row.id
            // var fd = {
            //   yynumber: parseInt(row.yynumber) - parseInt(row.lsyynumber),
            //   id: row.id,
            //   action: "yynumber"
            // }
            // update(fd).then(res => {
            //   this.tableDataorder[index].lsyynumber = parseInt(row.lsyynumber)
            //   this.tableDataorder[index].yynumber = parseInt(row.yynumber) - parseInt(row.lsyynumber)
            //   this.tableDataorder[index].islsyynumber = true
            //   this.$message.success(res.info)
            //   //this.tableData[index].cskuom = row.inputvaluec
            // });

          }).catch(() => {
            //this.tableData[index].cskuom = this.tableData[index].bakcskuom ? this.tableData[index].bakcskuom : null
            // this.$message({
            //   type: 'info',
            //   message: 'Cancelled'
            // });
          });
        }
      },
      handleremindertimeChange(value) {
        console.log('Date changed:', value);
        this.formData.remindertime = value
        this.$forceUpdate()
      },
      handleDateChange(value) {
        console.log('Date changed:', value);
        this.formData.addtime = value
        this.$forceUpdate()
      },
      handleRowClick(row, column, event) {
        this.$refs.singleSelectTable.clearSelection();
        this.$refs.singleSelectTable.toggleRowSelection(row, true);
        this.selectedRow = row;
        this.gotosaleordernumber = row.ordernumber
        this.tableDataorder = []
        console.log(row, "rowrowrowrowrow")
        var originalArray = row.saleorderproductslist
        for (let ib = 0; ib < originalArray.length; ib++) {
          originalArray[ib].lsyynumber = originalArray[ib].yynumber
          this.tableDataorder.push(originalArray[ib])
        }
      },
      qty(index, event) {
        const inputValue = event.target.value; // 获取输入的值
        const numberValue = parseFloat(inputValue) || 0; // 将输入值转换为浮点数，如果无法转换则为0
        const row = this.formData.procureditem[index]; // 获取当前行的数据
        if (numberValue > row.onhand) {
          row.qty = row.onhand;
        }
      },
      changeProduct(index, event) {
        for (var i = 0; i < this.formData.procureditem[index].batchnumberlist.length; i++) {
          var tm = this.formData.procureditem[index].batchnumberlist[i].batchnumber
          if (tm == this.formData.procureditem[index].batchnumber) {
            this.formData.procureditem[index].expirationdate = this.formData.procureditem[index].batchnumberlist[i]
              .expirationdate
            this.formData.procureditem[index].qty = this.formData.procureditem[index].batchnumberlist[i].quantity
            break;
          }
          this.$nextTick(() => {
            this.$forceUpdate()
          })
        }
      },
      isRowSelectable(row, selected) {
        return !this.oidlist.includes(row.id);
      },
      isRowSelectableorder(row, selected) {
        return !this.oidlist.includes(row.id);
      },
      isDisabled(id) {
        return this.oidlist.includes(id);
      },
      onOpen(id) { // 展开
        this.currentOpen = id;
      },
      onClose(id) { // 关闭
        if (this.currentOpen === id) {
          this.currentOpen = null;
        }
      },
      async sizeChange1(val) {
        this.page1.per_page = val;
        await this.fetchData1();
      },
      async currentChange1(val) {
        this.page1.current_page = val;
        await this.fetchData1();
      },
      async sizeChange2(val) {
        this.page2.per_page = val;
        await this.fetchData2();
      },
      async currentChange2(val) {
        this.page2.current_page = val;
        await this.fetchData2();
      },
      find1(event) {
        this.$nextTick().then(() => {
          this.page1.current_page = 1;
          this.fetchData1();
        });
      },
      async savepayment() {
        if (this.received > 0) {
          const data = {
            saleorders_id: this.id,
            received: this.received,
            recevicetime: this.recevicetime,
            totalamount: this.formData.totalamount,
            userid: this.formData.customer_id,
          };
          const {
            info
          } = await saleinvoicepaymentadd(data);
          this.$message.success("Edit successfully");
          this.payment = false;
        } else {
          this.$message.error("The received must be > 0 ");
        }
      },
      goiscustomersku() {
        var isaar = false;
        for (var i = 0; i < this.ids.length; i++) {
          var pid = this.ids[i]
          for (var iv = 0; iv < this.tableData1.length; iv++) {
            if (this.tableData1[iv].id == pid) {
              if (this.tableData1[iv].csku) {
                console.log(this.tableData1[iv].csku, "ddddddddddddddddd")
              } else {
                console.log(this.tableData1[iv].csku, "eeeeeeeeeeeeeeeee")
                isaar = true;
                return isaar;
              }
            }
          }
        }
        return isaar;
      },
      async handleadd() {
        for (var i = 0; i < this.ids.length; i++) {
          var pid = this.ids[i]
          for (var iv = 0; iv < this.tableData1.length; iv++) {
            if (this.tableData1[iv].id == pid) {
              if (this.oidlist.includes(pid)) {

              } else {
                this.oidlist.push(pid)
                this.tindex = this.formData.procureditem.length

                // inventorywaylist(1, 1, {
                //   product_id: pid,
                //   warehouse_id: this.warehouseid
                // }).then(res => {
                //   if (res.data) {
                //     this.tableData1[iv].preqty = res.data[0].quantity
                //   }
                // });

                this.addItem()
                this.tableData1[iv].availableqty = this.tableData1[iv].qty
                this.tableData1[iv].cskuom = this.tableData1[iv].cskuom
                this.tableData1[iv].uom = this.tableData1[iv].uom
                this.tableData1[iv].customersku = this.tableData1[iv].csku
                this.selectadd(this.tableData1[iv])

                this.$nextTick(() => {
                  this.$forceUpdate()
                })
              }
              //break
            }
          }
        }
        this.dialogFormVisible = false
      },
      async addv(row, oid) {
        if (row.csku) {
          if (this.oidlist.includes(oid)) {
            this.$message.error("The product has been added !")
          } else {
            this.oidlist.push(oid)
            console.log(row, "ddddddddddddddd")
            row.customer_id = this.cid;
            row.title = row.name
            this.productdata.push(row)
            let {
              store
            } = require(`@/api/${this.module}`);
            let {
              info
            } = await store({
              procureditem: this.productdata
            });
            this.$message.success(info);
            this.productdata = [];
            this.fetchData()
          }
        } else {
          this.$message.error("Please Enter Customer SKU")
        }
      },
      normalizer(node) {
        if (node.children && node.children.length === 0) {
          delete node.children;
        }
        return {
          id: node.id,
          label: node.name,
          children: node.children
        };
      },
      handleTree(data, id, parentId, children) {
        let config = {
          id: id || 'id',
          parentId: parentId || 'parentId',
          childrenList: children || 'children'
        };

        var childrenListMap = {};
        var nodeIds = {};
        var tree = [];

        for (let d of data) {
          let parentId = d[config.parentId];
          if (childrenListMap[parentId] == null) {
            childrenListMap[parentId] = [];
          }
          nodeIds[d[config.id]] = d;
          childrenListMap[parentId].push(d);
        }

        for (let d of data) {
          let parentId = d[config.parentId];
          if (nodeIds[parentId] == null) {
            tree.push(d);
          }
        }

        for (let t of tree) {
          adaptToChildrenList(t);
        }

        function adaptToChildrenList(o) {
          if (childrenListMap[o[config.id]] !== null) {
            o[config.childrenList] = childrenListMap[o[config.id]];
          }
          if (o[config.childrenList]) {
            for (let c of o[config.childrenList]) {
              adaptToChildrenList(c);
            }
          }
        }
        return tree;
      },

      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.multiplev = !selection.length
      },
      handleSelectionChange2(selection) {
        // this.sids = selection.map(item => item.id)
        // this.multiplevs = !selection.length
        // this.tableDataorder = []
        // for (var i = 0; i < selection.length; i++) {
        //   var originalArray = selection[i].saleorderproductslist
        //   for (let ib = 0; ib < originalArray.length; ib++) {
        //     this.tableDataorder.push(originalArray[ib])
        //   }
        // }
        console.log(this.tableDataorder, "this.tableDataorderewwe")
      },
      handleSelectionChangeorder(selection) {
        this.idso = selection.map(item => item.id)
        this.multiplevo = !selection.length
      },
      handleorderadd() {
        console.log(this.idso, "this.idso")
        for (var i = 0; i < this.idso.length; i++) {
          var pido = this.idso[i]
          console.log(pido, "this.pido")
          for (var iv = 0; iv < this.tableDataorder.length; iv++) {
            console.log(this.tableDataorder[iv].id, "this.tableDataorder[iv].product_id")



            if (this.tableDataorder[iv].id == pido) {
              // if (this.oidlist.includes(pido)) {

              // } else {
              console.log("开始插入  数据：" + pido)
              //this.oidlist.push(pido)

              const id = this.tableDataorder[iv].id
              var fd = {
                yynumber: parseInt(this.tableDataorder[iv].yynumber) - parseInt(this.tableDataorder[iv].lsyynumber),
                id: this.tableDataorder[iv].id,
                action: "yynumber"
              }
              this.tableDataorder[iv].addbyinvid = this.tableDataorder[iv].id
              this.tableDataorder[iv].addbyinvidyynumber = parseInt(this.tableDataorder[iv].yynumber)
              // update(fd).then(res => {
              //   this.tableDataorder[index].lsyynumber = parseInt(this.tableDataorder[iv].lsyynumber)
              //   this.tableDataorder[index].yynumber = parseInt(this.tableDataorder[iv].yynumber) - parseInt(this
              //     .tableDataorder[iv].lsyynumber)
              //   this.tableDataorder[iv].islsyynumber = true
              // });
              this.$nextTick(() => {
                this.$forceUpdate()
              })


              this.tableDataorder[iv].batchnumberlist = this.tableDataorder[iv].batchnumberlist
              this.tableDataorder[iv].name = this.tableDataorder[iv].productname
              this.tableDataorder[iv].customersku = this.tableDataorder[iv].suppliesku
              this.tableDataorder[iv].id = this.tableDataorder[iv].product_id;
              this.tableDataorder[iv].availableqty = this.tableDataorder[iv].onhand;
              this.tableDataorder[iv].qty = this.tableDataorder[iv].lsyynumber;
              this.tableDataorder[iv].uom = this.tableDataorder[iv].unit;
              this.tableDataorder[iv].cskuom = this.tableDataorder[iv].cskuom;
              this.tableDataorder[iv].price = this.tableDataorder[iv].costprice;
              this.tableDataorder[iv].ordernumber = this.gotosaleordernumber
              this.tindex = this.formData.procureditem.length
              this.addItem()
              this.selectadd(this.tableDataorder[iv])
              this.$nextTick(() => {
                this.$forceUpdate()
              })
              //}
            }
          }
        }
        this.dialogFormVisible1 = false

      },
      productadd() {
        this.fetchData1()
        this.dialogFormVisible = true
      },
      productsaleorder() {
        this.fetchData2()
        this.tableDataorder = []
        this.dialogFormVisible1 = true
      },
      async fetchData2() {
        let {
          index
        } = require(`@/api/saleorder`);
        //this.searchForm2.status = "approved"
        const res = await index(
          this.page2.current_page,
          this.page2.per_page,
          this.searchForm2
        );
        // if (
        //   res.data instanceof Object &&
        //   typeof this.transfromData === "function"
        // ) {
        //   let data = this.transfromData(res.data);
        //   this.tableData2 = data;
        // } else {
        //   this.tableData2 = res.data;
        // }
        // console.log(res.meta)

        if (res.data instanceof Object && typeof this.transfromData === "function") {
          let data = this.transfromData(res.data);
          // 筛选数据
          data = data.map(item => {
            if (item.saleorderproductslist && Array.isArray(item.saleorderproductslist)) {
              item.saleorderproductslist = item.saleorderproductslist.filter(product =>
                product.yynumber > 0
              );
            }
            return item;
          }).filter(item =>
            item.saleorderproductslist && item.saleorderproductslist.length > 0
          );
          if (res.meta) {
            this.isPaginate2 = true;
            res.meta.per_page = parseInt(res.meta.per_page);
            res.meta.total = data.length; // 更新总数为过滤后的数量
            this.page2 = Object.assign(this.page2, res.meta);

            // 如果当前页没有数据，回到第一页
            if (data.length === 0 && this.page2.current_page > 1) {
              this.page2.current_page = 1;
              await this.fetchData2();
              return;
            }
          }

          this.tableData2 = data;
        } else {
          this.tableData2 = res.data;
          if (res.meta) {
            this.isPaginate2 = true;
            res.meta.per_page = parseInt(res.meta.per_page);
            this.page2 = Object.assign(this.page2, res.meta);
          }
        }



        // if (res.meta) {
        //   this.isPaginate2 = true;
        //   res.meta.per_page = parseInt(res.meta.per_page);
        //   this.page2 = Object.assign(this.page2, res.meta);
        // } else {
        //   this.isPaginate2 = false; // 不分页
        // }



      },
      async fetchData1() {
        const res = await skulist(
          this.page1.current_page,
          this.page1.per_page,
          this.searchForm1
        );
        if (
          res.data instanceof Object &&
          typeof this.transfromData === "function"
        ) {
          let data = this.transfromData(res.data);
          this.tableData1 = data;
        } else {
          this.tableData1 = res.data;
        }
        console.log(res.meta)
        if (res.meta) {
          this.isPaginate1 = true;
          res.meta.per_page = parseInt(res.meta.per_page);
          this.page1 = Object.assign(this.page1, res.meta);
        } else {
          this.isPaginate1 = false; // 不分页
        }
      },
      onCloseDialog() {
        this.caigou1 = false;
        this.caigou2 = false;
        this.caigou3 = false;
      },
      prints(index) {
        if (index == 1) {
          this.caigou1 = true;
        }
        if (index == 2) {
          this.caigou2 = true;
        }
        if (index == 3) {
          this.caigou3 = true;
        }
        this.printform = this.formData;
        console.log(this.printform)
      },
      async changeterm(value) {
        const selectedTerm = this.customers.find(item => item.id === value);
        if (selectedTerm) {

          this.$set(this.formData, 'creditterm', selectedTerm.crediterm || '')
          this.$set(this.formData, 'currency', selectedTerm.currency || '')
          this.$set(this.formData, 'customercredit', selectedTerm.creditlimit || '')

          try {
            var {
              data
            } = await billingindex(1, 100, {
              customer_id: value,
              type: 1
            });
            this.billingtitle = data
            if (this.billingtitle.length > 0) {
              this.$set(this.formData, 'billingtitle', this.billingtitle[0].title || '')
              this.$set(this.formData, 'billingattention', this.billingtitle[0].attention || '')
              this.$set(this.formData, 'billingfax', this.billingtitle[0].fax || '')
              this.$set(this.formData, 'billingtel', this.billingtitle[0].tel || '')
              this.$set(this.formData, 'billingaddress', this.billingtitle[0].address || '')
              this.$nextTick(() => {
                this.$forceUpdate()
              })

            } else {

              this.$set(this.formData, 'billingtitle', '')
              this.$set(this.formData, 'billingattention', "")
              this.$set(this.formData, 'billingfax', '')
              this.$set(this.formData, 'billingtel', "")
              this.$set(this.formData, 'billingaddress', '')
            }
            var {
              data
            } = await deliveryindex(1, 100, {
              customer_id: value,
              type: 1
            });
            this.deliverytitle = data
            if (this.deliverytitle.length > 0) {
              this.$set(this.formData, 'deliverytitle', this.deliverytitle[0].title || '')
              this.$set(this.formData, 'deliveryattention', this.deliverytitle[0].attention || '')
              this.$set(this.formData, 'deliveryfax', this.deliverytitle[0].fax || '')
              this.$set(this.formData, 'deliverytel', this.deliverytitle[0].tel || '')
              this.$set(this.formData, 'deliveryaddress', this.deliverytitle[0].address || '')
              this.$nextTick(() => {
                this.$forceUpdate()
              })
            } else {
              this.$set(this.formData, 'deliverytitle', '')
              this.$set(this.formData, 'deliveryattention', "")
              this.$set(this.formData, 'deliveryfax', '')
              this.$set(this.formData, 'deliverytel', "")
              this.$set(this.formData, 'deliveryaddress', '')
            }
          } catch (error) {
            console.error('Failed to fetch customer:', error);
          }

        }
      },
      changebt(value) {
        const selectedbt = this.billingtitle.find(item => item.title === value);
        if (selectedbt) {
          this.$set(this.formData, 'billingattention', selectedbt.attention || '')
          this.$set(this.formData, 'billingfax', selectedbt.fax || '')
          this.$set(this.formData, 'billingtel', selectedbt.tel || '')
          this.$set(this.formData, 'billingaddress', selectedbt.address || '')

        } else {
          this.$set(this.formData, 'billingattention', '')
          this.$set(this.formData, 'billingfax', "")
          this.$set(this.formData, 'billingtel', '')
          this.$set(this.formData, 'billingaddress', "")
        }
        this.$forceUpdate()
      },
      changedt(value) {
        const selecteddt = this.deliverytitle.find(item => item.title === value);
        if (selecteddt) {
          this.$set(this.formData, 'deliveryattention', selectedbt.attention || '')
          this.$set(this.formData, 'deliveryfax', selectedbt.fax || '')
          this.$set(this.formData, 'deliverytel', selectedbt.tel || '')
          this.$set(this.formData, 'deliveryaddress', selectedbt.address || '')
        } else {
          this.$set(this.formData, 'deliveryattention', "")
          this.$set(this.formData, 'deliveryfax', '')
          this.$set(this.formData, 'deliverytel', "")
          this.$set(this.formData, 'deliveryaddress', '')
        }
        this.$forceUpdate()
      },
      showButton(index) {
        if (isdiable || isapproved) {
          return
        }
        this.hoveredIndex = index; // 设置当前鼠标悬停的行的索引
      },
      hideButton(index) {
        if (isdiable) {
          return
        }
        if (this.hoveredIndex === index) {
          this.hoveredIndex = null; // 清除当前鼠标悬停的行的索引
        }
        // 注意：这里其实不需要传入 index，因为 mouseleave 事件已经足够判断鼠标离开了当前元素
        // 但为了保持与 showButton 方法参数的一致性，这里还是传入了 index（尽管未使用）
      },
      delcart(index) {
        this.formData.procureditem[index].certificates = null
      },
      getUploadHandler(index) {
        // 返回一个函数，该函数将作为 http-request 的处理器
        return (options) => {
          // 在这里，我们可以安全地使用 index，因为它是在这个闭包中捕获的
          this.rowIndex = index; // 如果需要在 uploadHandle 中使用，可以临时存储到组件的 data 或 properties 中
          this.uploadHandle(options);
        };
      },
      async uploadHandle(options) {
        const file = options.file;
        if (file) {
          this.fileReader.readAsDataURL(file);
        }
        this.fileReader.onload = () => {
          const formData = new FormData();
          formData.append("file", file);
          uploadImg(formData)
            .then((res) => {
              console.log(res)
              var {
                data
              } = res;
              this.$message.success(res.status);
              this.formData.procureditem[this.rowIndex].certificates = data.url
            })
            .catch((err) => {
              if (err.response.status === 422) {
                const {
                  info,
                  fileName
                } = err.response.data;
                this.$message.error(info);
              }
            });
        };

      },
      godisable() {
        this.isdiable = !this.isdiable
      },
      addItem() { //增加行
        this.xiabiao += 1
        this.formData.procureditem.push({
          index: this.xiabiao,
          productname: "",
          sku: "",
          suppliesku: "",
          onhand: "",
          qty: "",
          unit: "",
          cskuom: "",
          costprice: "",
          costamount: "",
          saleprice: "",
          expirationdate: "",
          certificates: "",
          batchnumber: "",
          note: "",
          product_id: "",
          ordernumber: "",
          preqty: 0,
          batchnumberlist: "",
          addbyinvid: 0,
          addbyinvidyynumber: 0
        });
      },
      addItem1() {

      },
      addItem2() {


      },
      close() {
        this.$router.push({
          path: '/salemodel/saleinvoice'
        });
      },
      removeItem(row) {
        const index = this.formData.procureditem.indexOf(row)
        if (this.formData.procureditem.length > 1) {
          this.formData.procureditem.splice(index, 1);
        } else {
          this.$message.error("Keep at least one row of data!")
        }
      },
      async editstatus(id, statusdata) {
        console.log(id)
        try {
          await this.$confirm(
            "This operation will permanently Save status. Do you want to continue?",
            "prompt", {
              confirmButtonText: "Confirm",
              cancelButtonText: "Cancel",
              type: "warning"
            });
          let {
            info
          } = await update({
            id: id,
            action: "status",
            status: statusdata
          });
          this.$message.success("Status update successful");
          this.isapproved = true

          // 刷新当前页
          const {
            data
          } = await show(this.id);
          this.formData = data;
          if (this.formData.status == "approved") {
            this.isapproved = true
          }
          if (this.formData.status == "rejection") {
            this.isapproved = false
            this.isdiable = true
            this.formData.status == "rejection"
          }
        } catch (error) {
          this.$message({
            type: "info",
            message: "Cancelled save"
          });
        }
      },
      selectadd(row) {
        if (row) {
          inventorywaylist(1, 1, {
            product_id: row.id,
            warehouse_id: this.warehouseid
          }).then(res => {
            if (res.data) {
              this.formData.procureditem[this.tindex].preqty = res.data[0].quantity ? res.data[0].quantity : 0
            }
          });
          this.formData.procureditem[this.tindex].productname = row.name
          this.formData.procureditem[this.tindex].qty = row.qty ? row.qty : 0
          this.formData.procureditem[this.tindex].sku = row.sku
          this.formData.procureditem[this.tindex].onhand = row.availableqty
          this.formData.procureditem[this.tindex].unit = row.uom
          this.formData.procureditem[this.tindex].cskuom = row.cskuom
          this.formData.procureditem[this.tindex].costprice = row.price
          this.formData.procureditem[this.tindex].product_id = row.id
          this.formData.procureditem[this.tindex].suppliesku = row.customersku
          this.formData.procureditem[this.tindex].ordernumber = row.ordernumber
          this.formData.procureditem[this.tindex].preqty = this.formData.procureditem[this.tindex].preqty ? this
            .formData.procureditem[this.tindex].preqty : 0

          this.formData.procureditem[this.tindex].batchnumberlist = row.batchnumberlist
          if (row.batchnumberlist.length > 0) {
            this.formData.procureditem[this.tindex].batchnumber = row.batchnumberlist[0]
              .batchnumber
            this.formData.procureditem[this.tindex].expirationdate = row.batchnumberlist[0]
              .expirationdate
          } else {

          }
          this.formData.procureditem[this.tindex].addbyinvid = row.addbyinvid ? row.addbyinvid : 0

          this.formData.procureditem[this.tindex].addbyinvidyynumber = row.addbyinvidyynumber ? row.addbyinvidyynumber :
            0
          this.isgoprolist = false;
        }
      },
      onChangeproductname(proname, index, event) {
        this.$nextTick(() => {
          this.topx = this.x + "px";
          console.log('Input coordinates:', this.x, this.y);
        });
        if (proname) {
          if (this.formData.staff) {
            warehouselist(1, 1, {
              belongingsales: this.formData.staff,
            }).then(res => {
              if (res.data) {
                this.warehouseid = res.data[0].id
                this.tindex = index
                prowarlist(1, 10000, {
                  name: proname,
                  // customer_id: this.formData.customer_id,
                  warehouseid: res.data[0].id
                }).then(res => {
                  this.tableData = res.data
                  this.isgoprolist = true;
                });
              }
            });
          } else {
            this.tindex = index
            prowarlist(1, 10000, {
              name: proname,
              customer_id: this.formData.customer_id,
            }).then(res => {
              this.tableData = res.data
              this.isgoprolist = true;
            });
          }
        }
      },
      onChangeproductsku(sku, index, event) {
        console.log(index)
        this.$nextTick(() => {
          this.topx = this.x + "px";
          console.log('Input coordinates:', this.x, this.y);
        });
        if (sku) {
          if (this.formData.staff) {
            warehouselist(1, 1, {
              belongingsales: this.formData.staff,
            }).then(res => {
              if (res.data) {
                this.tindex = index
                prowarlist(1, 10000, {
                  sku: sku,
                  warehouse_id: res.data[0].id
                }).then(res => {
                  this.tableData = res.data
                  this.isgoprolist = true;
                });
              }
            });
          }
        }
      },
      checkDataAndGetPosition(inputElement) {
        if (inputElement.value === '') {
          setTimeout(() => {
            this.checkDataAndGetPosition(inputElement);
          }, 1000); // 等待1秒后再次尝试获取数据
        } else {
          const inputRect = inputElement.getBoundingClientRect();
          const inputCoordinates = {
            x: inputRect.left,
            y: inputRect.top
          };
          console.log('Input coordinates:', inputCoordinates);
        }
      },
      handleClick(tab, event) {
        console.log(tab, event);
      },
      edit(id) {
        this.$router.push({
          path: '/product/editproduct',
          query: {
            id: id
          }
        })
      },
      onOpen(id) { // 展开
        this.currentOpen = id;
      },
      onClose(id) { // 关闭
        if (this.currentOpen === id) {
          this.currentOpen = null;
        }
      },
      async saveOrder(row) {
        let data = {
          id: row.id,
          order: row.order,
          action: "order"
        };
        row.isEdit = false;
        let {
          info
        } = await update(data);
        this.fetchData();
      },
      transfromData(data) {
        let result = data.map((item) => {
          item.isEdit = false;
          return item;
        });
        return result;
      },
      saveHandle(form) {
        this.save(form);
      },
      async save(form) {
        this.$refs[form].validate(async (valid) => {
          if (valid) {
            try {
              this.isubmit = true

              console.log(this.formData.procureditem, "dddddddddddddddddddddddddddddd")

              for (var i = 0; i < this.formData.procureditem.length; i++) {
                var tm = this.formData.procureditem[i].productname
                if (tm == "") {
                  this.$message.error("Please add a product data");
                  this.isubmit = false
                  return false
                }
                var tm = this.formData.procureditem[i].qty
                if (tm == "") {
                  this.$message.error("Please add a product qty");
                  this.isubmit = false
                  return false
                }
                var tm = this.formData.procureditem[i].costprice
                if (tm == "") {
                  this.$message.error("Please add a product saleprice");
                  this.isubmit = false
                  return false
                }
                var tm = this.formData.procureditem[i].expirationdate
                if (tm == "") {
                  this.$message.error("Please add a product expirationdate");
                  this.isubmit = false
                  return false
                }
                if (this.formData.procureditem[i].addbyinvid) {
                  var fd = {
                    yynumber: parseInt(this.formData.procureditem[i].addbyinvidyynumber - this
                      .formData.procureditem[i].qty),
                    id: this.formData.procureditem[i].addbyinvid,
                    action: "yynumber"
                  }
                  update(fd).then(res => {});
                }

              }

              this.formData.totalqty = this.totalqty
              console.log(this.totalqty)
              this.formData.totalamount = this.totalamount
              console.log(this.totalamount)
              for (var i = 0; i < this.customers.length; i++) {
                if (this.formData.customer_id == this.customers[i].id) {
                  this.formData.customername = this.customers[i].name
                }
              }

              if (this.formData.staff) {
                console.log(this.formData.staff, "JavaJavaJavaJava")
                const staffinfo = this.staff.find(item => item.name === this.formData.staff);
                console.log(staffinfo, "bbbbbbbbbbbbbbbbbbbbbb")
                if (staffinfo) {
                  this.formData.staffid = staffinfo.id
                }
              }

              if (this.isEdit) {
                let {
                  update
                } = require(`@/api/${this.module}`);
                let {
                  info
                } = await update(this.formData);
                this.$message.success("Edit successfully");
                setTimeout(() => {
                  this.$store.dispatch('tagsView/delView', this.$route);
                  this.$router.push({
                    path: '/salemodel/saleinvoice'
                  });
                }, 1000);
              }
              if (this.isNew) {
                if (this.formData.procureditem != null && this.formData.procureditem
                  .length > 0) {

                } else {
                  this.$message.error("Please add a product");
                  return false
                }
                let {
                  store
                } = require(`@/api/${this.module}`);
                let info1 = await store(this.formData);
                if (info1) {
                  if (info1.status_code = 201) {
                    this.$message.success("Add successfully");
                    setTimeout(() => {
                      this.$store.dispatch('tagsView/delView', this.$route);
                      this.$router.push({
                        path: '/saleinvoice/editsaleinvoice',
                        query: {
                          id: info1.info
                        }
                      })
                    }, 1000);
                  } else {
                    this.isubmit = false
                    this.$message.error("Data verification error");
                    return false;
                  }
                }
              }
              this.fetchData();
              this.isEdit = false;
              this.isNew = false;
              this.isubmit = false
              this.dialogFormVisible = false;
            } catch (error) {
              let result = error.response.data;
              this.$message.error(result.info);
            }
          } else {
            this.isubmit = false
            this.$message.error(
              "Data verification error, please input according to the specified rules"
            );
            return false;
          }
        });
      },
      async avatarUpload(options) {
        const file = options.file;
        if (file) {
          this.fileReader.readAsDataURL(file);
        }
        this.fileReader.onload = async () => {
          const formData = new FormData();
          formData.append("file", file);
          uploadImg(formData)
            .then((res) => {
              const {
                data
              } = res;
              this.formData.image = data.url;
              //this.save("ruleForm");
            })
            .catch((err) => {
              options.onError(err);
            });
        };
      },
      changeAvatar(file, fileList) {
        console.log("sssssssssssssssssss")
        const reader = new window.FileReader();
        reader.readAsDataURL(new Blob([file.raw]));
        reader.onload = (e) => {
          this.formData.image = reader.result;
          this.imageUrl = reader.result;
          this.isUploadFile = true;
          console.log(reader.result)
        };
      },
      async changeStatus(row) {
        let tips = "";
        if (row.status) {
          tips = "是否启用该文章?";
        } else {
          tips = "是否禁用该文章?";
        }
        this.$confirm(tips, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
          .then(async () => {
            let data = {
              id: row.id,
              status: row.status,
              action: "status"
            };
            let {
              info
            } = await update(data);
            this.$message.success(info);
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "Cancelled deletion"
            });
          });
      }

    }
  }
</script>
<style>
  table {
    border-collapse: collapse;
    border-spacing: 0;
  }

  .bba .el-dialog__body {
    padding: 30px 20px !important;
    color: #606266;
  }

  .ordernumber {
    border: 0px;
    text-align: left;
    font-weight: 600;
    position: relative;
    left: 48%;
    display: inline-block;
    top: 130px;
    font-size: 25px;
    height: 40px;
    line-height: 40px;
    width: 200px;
  }

  .layui-card-body .layui-table {
    margin: 5px 0;
  }

  .layui-table {
    width: 100%;
    background-color: #fff;
    color: #666;
  }

  .layui-table tbody tr:hover,
  .layui-table thead tr,
  .layui-table-click,
  .layui-table-header,
  .layui-table-hover,
  .layui-table-mend,
  .layui-table-patch,
  .layui-table-tool,
  .layui-table-total,
  .layui-table-total tr,
  .layui-table[lay-even] tr:nth-child(even) {
    background-color: #f2f2f2;
  }

  .layui-table th {
    text-align: left;
    font-weight: 400;
  }

  .layui-table td,
  .layui-table th,
  .layui-table-col-set,
  .layui-table-fixed-r,
  .layui-table-grid-down,
  .layui-table-header,
  .layui-table-page,
  .layui-table-tips-main,
  .layui-table-tool,
  .layui-table-total,
  .layui-table-view,
  .layui-table[lay-skin=line],
  .layui-table[lay-skin=row] {
    border-width: 1px;
    border-style: solid;
    border-color: #eee;
  }

  .layui-table td,
  .layui-table th {
    position: relative;
    padding: 9px 15px;
    min-height: 20px;
    line-height: 20px;
    text-align: center;
    font-size: 14px;
  }

  .layui-btn:not(.layui-btn-lg):not(.layui-btn-sm):not(.layui-btn-xs) {
    height: 34px;
    line-height: 34px;
    padding: 0 8px;
  }

  .layui-table-view .layui-table td,
  .layui-table[lay-skin=line] th {
    border-width: 0 0 1px !important;
  }

  .layuimini-container .layui-table-box .layui-table-header th {
    font-weight: bold !important;
    color: #565656 !important;
  }

  .layui-table[lay-skin=line] td,
  .layui-table[lay-skin=line] th {
    border-width: 0 0 1px;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
<style>
  .avatar-uploader {
    position: relative;
  }

  .customWidth {
    width: 80%;
  }

  .tableDatav .has-gutter {
    display: none;
  }

  .cadd {
    width: 100%;
  }

  .plt {
    position: absolute;
    z-index: 9999;
    left: 170px;
    background-color: #f5f5f5;
  }

  #cadd .el-table th.el-table__cell>.cell {
    display: inline-block;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    position: relative;
    vertical-align: middle;
    padding-left: 10px;
    padding-right: 10px;
    width: 100%;
    font-weight: 600 !important;
    color: #000;
    font-size: 14px !important;
  }
</style>
<style>
  @media print {
    .your-background-class {
      -webkit-print-color-adjust: exact !important;
      /* 对于 WebKit 浏览器 */
      print-color-adjust: exact !important;
      /* 对于支持该属性的其他浏览器，尽管目前很少 */
    }
  }

  .el-dialog__body {
    padding: 0;
  }

  .warpper {
    padding: 30px 20px;
    color: #606266;
    font-size: 14px;
    word-break: break-all;
  }

  .table,
  .toolbar,
  .page {
    margin: 20px;
  }

  .toolbar {
    margin-top: 10px;
    padding: 5px;
  }

  .table {
    margin-bottom: 10px;
  }

  .page {
    margin-top: 10px;
    text-align: center;
  }

  .green-text {
    color: green;
  }

  .red-text {
    color: red;
  }

  .yellow-text {
    color: yellow;
  }
</style>
